﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Data;

namespace HY.Common
{
    public class ModelHelper
    {
        /// <summary>
        /// 获取类字段名及显示名字典
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Dictionary<string, string> ColumnMapping<T>()
        {
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (var p in properties)
            {
                var attr = p.GetCustomAttribute<DisplayNameAttribute>();
                string displayName = attr == null ? p.Name : attr.DisplayName;
                dic.Add(p.Name, displayName);
            }
            return dic;
        }
        /// <summary>
        /// 动态绑定ListView列
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private static GridView BindColumns<T>()
        {
            GridView gv = new GridView();
            foreach (var item in ColumnMapping<T>())
            {
                GridViewColumn gvc = new GridViewColumn();
                gvc.Header = item.Value;//列头显示
                gvc.DisplayMemberBinding = new Binding(item.Key);//绑定
                gv.Columns.Add(gvc);
            }
            return gv;
        }
    }
}
